
import React, { useEffect, useState } from 'react';
import {
  Card,
  Checkbox,
  Dialog,
  DialogProps, FormProps,
  MessagePlugin,
  Radio,
  Textarea,
  Switch,
  Tooltip,
  Link,
  PrimaryTable,
  Pagination,
  Message,

} from 'tdesign-react';
import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon } from 'tdesign-icons-react';

import axios from 'axios';
import { flushSync } from 'react-dom';

import {
  Button,
  Cascader,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Mentions,
  Select,
  TreeSelect,
  Segmented,
  Space,
  Table,
  Tag,
  Modal,
  Tabs,
} from 'antd';

import type { TableProps } from 'antd';

import { message } from 'antd';
import TabPane from 'antd/es/tabs/TabPane';
axios.defaults.baseURL = 'http://127.0.0.1:3000/zlq'


export default function Management() {
  const [form] = Form.useForm()

  const [visible, setVisible] = useState(false);
  const handleClick = () => {
    setVisible(true);
  };
  const onConfirm: DialogProps['onConfirm'] = async (context) => {
    let form = {
      authority: authority,
      grouping: grouping,
      entry: entry,
      name: name,
      content: content,
      state: state
    }
    let { data: { code } } = await axios.post('managementadd', form)
    if (code == 200) {
      getManagementList()
      setAuthority('')
      setGrouping("")
      setEntry("")
      setName("")
      setContent("")
      setState("")
    }
    console.log('点击了确认按钮', context);
    setVisible(false);
  };
  const onCancel: DialogProps['onCancel'] = (context) => {
    setAuthority('')
    setGrouping("")
    setEntry("")
    setName("")
    setContent("")
    setState("")
    setVisible(false);
    console.log('点击了取消按钮', context);
  };
  const onClickCloseBtn: DialogProps['onCloseBtnClick'] = (context) => {
    setAuthority('')
    setGrouping("")
    setEntry("")
    setName("")
    setContent("")
    setState("")
    console.log('点击了关闭按钮', context);
  };
  const onKeydownEsc: DialogProps['onEscKeydown'] = (context) => {
    console.log('按下了ESC', context);
  };
  const onClickOverlay: DialogProps['onOverlayClick'] = (context) => {
    console.log('点击了蒙层', context);
  };
  const handleClose: DialogProps['onClose'] = (context) => {
    console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发', context);
    setVisible(false);
  };
  // const name = Form.useWatch('name', form);
  const gender = Form.useWatch('gender', form);
  // console.log('name', name);
  console.log('gender', gender);

  const onSubmit: FormProps['onSubmit'] = (e) => {
    console.log(e);
    if (e.validateResult === true) {
      MessagePlugin.info('提交成功');
    }
  };

  const onReset: FormProps['onReset'] = (e) => {
    console.log(e);
    MessagePlugin.info('重置成功');
  };

  const setMessage = () => {
    console.log(form);
    form.setFields([
      { name: 'name', status: 'error', validateMessage: { type: 'error', message: '输入有误' } },
      { name: 'birthday', status: 'warning', validateMessage: { type: 'warning', message: '时间有误' } },
    ]);
  };
  const [authorityList, setAuthorityList] = useState([]);
  const [groupingList, setGroupingList] = useState([]);
  const [ManagementList, setManagementList] = useState([])

  const [id, setId] = useState('')
  const [authority, setAuthority] = useState('')
  const [grouping, setGrouping] = useState('')
  const [entry, setEntry] = useState('')
  const [name, setName] = useState('')
  const [content, setContent] = useState('')
  const [state, setState] = useState('')

  const getauthority = async () => {
    let { data: { code, authorityList } } = await axios.get('/authorityList')
    if (code == 200) {
      setAuthorityList(authorityList)
    }
  }
  const getGrouping = async () => {
    let { data: { code, groupingList } } = await axios.get('/groupingList')
    if (code == 200) {
      setGroupingList(groupingList)
      setGrouping_data(groupingList)
    }
  }

  let [so_name, setSo_Name] = useState('')
  let so_state = ''
  let [optionList, setOptionList] = useState([
    { id: 1, name: false, value: "禁用" }, { id: 2, name: true, value: "启用" }
  ])

  const getManagementList = async () => {
    let { data: { code, managementList, total } } = await axios.get(`/managementList?page=${page}&pagesize=${pageSize}&name=${so_name}&state=${so_state}`)
    if (code == 200) {
      setTotal(total)
      setManagementList(managementList)
      setData(managementList)
    }
  }

  let page = 1
  let pageSize = 2
  let [total, setTotal] = useState(0)

  const onChange: PaginationProps['onChange'] = (pageInfo) => {
    page = pageInfo.current
    pageSize = pageInfo.pageSize
    getManagementList()
    console.log(pageInfo);
  };
  const onPageSizeChange: PaginationProps['onPageSizeChange'] = (size) => {
    pageSize = size
    getManagementList()
    console.log('page-size:', size);
  };
  const onCurrentChange: PaginationProps['onCurrentChange'] = (index, pageInfo) => {
    page = index
    getManagementList()
    console.log(`转到第${index}页`);
    console.log(pageInfo);
  };


  const getState = (value: string) => {
    so_state = value
    getManagementList()
  }

  const getName = (e) => {
    if (e.key === 'Enter') {  // 判断是否是回车键
      console.log('回车键被按下，执行搜索');
      // 在这里触发搜索逻辑
      // 例如，调用一个搜索 API，或者根据 so_name 进行搜索
      getManagementList()
    }
  };

  const getEdit = (id: any) => {
    showModal()
    console.log(id);
    setId(id._id);
    setAuthority(id.authority);
    setGrouping(id.grouping);
    setContent(id.content);
    setEntry(id.entry);
    setState(id.state);
    setName(id.name);
    setVisible(true);
  };

  const getUpdate = async () => {
    let form = {
      _id: id,
      authority: authority._id,
      grouping: grouping._id,
      entry: entry,
      name: name,
      content: content,
      state: state
    }
    let { data: { code } } = await axios.post('managementupd', form)
    if (code == 200) {
      getManagementList()
      setId('')
      setAuthority('')
      setGrouping("")
      setEntry("")
      setName("")
      setContent("")
      setState("")
      handleOk()
    }
  }

  const getAdd = async () => {
    let form = {
      authority: authority._id,
      grouping: grouping._id,
      entry: entry,
      name: name,
      content: content,
      state: state
    }
    console.log(authority, grouping, 'awaaa');

    let { data: { code } } = await axios.post('managementadd', form)
    if (code == 200) {
      getManagementList()
      setAuthority('')
      setGrouping("")
      setEntry("")
      setName("")
      setContent("")
      setState("")
      handleOk()
    }
  }

  const [messageApi, contextHolder] = message.useMessage();

  //词条删除
  const getDel = async (id) => {
    let { data: { code } } = await axios.delete(`managementdel?_id=${id}`)
    if (code == 200) {
      getManagementList()
    }
  }

  const variant = Form.useWatch('variant', form);

  // 提交表单时的操作
  const onFinish = (values) => {
    console.log(values);
    // 你可以在这里发送这些数据到后台
  };

  interface DataType {
    key: string;
    name: string;
    entry: number;
    address: string;
    tags: string[];
  }

  //词条表格
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '词条编码',
      dataIndex: 'entry',
      key: 'entry',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '词条名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '词条内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '启用状态',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, row) => (
        <Space size="middle">
          {row.state ? (
            <p style={{ color: "green" }}>启用</p>
          ) : (
            <p style={{ color: "red" }}>禁用</p>
          )}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => { getEdit(record) }}>编辑</a>
          <a style={{ color: "red" }} onClick={()=>{getDel(record._id)}}>删除</a>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState<DataType[]>([]);

  //词条回显
  useEffect(() => {
    form.setFieldsValue({
      authority: authority._id || "",
      name: name,
      grouping: grouping._id || "",
      content: content,
      entry: entry,
      state: state,
    });
  }, [authority, name, grouping, content, entry, state]);

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };


  //新增词条弹框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setId('')
    setAuthority('')
    setGrouping("")
    setEntry("")
    setName("")
    setContent("")
    setState("")
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const { TabPane } = Tabs;

  //词条权限分类
  // 用来存储当前选中的分类
  const [selectedCategory, setSelectedCategory] = useState('category1');
  // 用来存储搜索的关键字
  const [searchQuery, setSearchQuery] = useState('');
  // 存储各个分类的搜索选项
  const [selectedOption, setSelectedOption] = useState(null);


  // 处理分类选择
  const handleCategoryChange = (key) => {
    setSelectedCategory(key);
    setSearchQuery('');  // 切换分类时清空搜索框
    setSelectedOption(null);  // 清空已选选项
  };

  const getGroupingAdd = async () => {
    let form = {
      name: groupingName,
    }
    let { data: { code } } = await axios.post('groupingadd', form)
    if (code == 200) {
      getGrouping()
      setGroupingName('')
    }
  }

  const grouping_columns: TableProps<DataType>['columns'] = [
    {
      title: '分组名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => { getGroupingEdit(record) }}>编辑</a>
          <a style={{ color: "red" }} onClick={()=>{getGroupingDel(record._id)}}>删除</a>
        </Space>
      ),
    },
  ];

  const [grouping_data, setGrouping_data] = useState<DataType[]>([]);
  const [groupingName, setGroupingName] = useState('')
  const [grouping_id,setGrouping_id] = useState('')

  const getGroupingEdit=(id)=>{
    setGrouping_id(id._id)
    setGroupingName(id.name)
  }

  const groupingUpdate=async()=>{
    let form = {
      _id: grouping_id,
      name: groupingName,
    }
    let { data: { code } } = await axios.post('groupingupd', form)
    if (code == 200) {
      getGrouping()
      setGrouping_id('')
      setGroupingName("")
    }
  }

  const getGroupingDel = async (id) => {
    let { data: { code } } = await axios.delete(`groupingdel?_id=${id}`)
    if (code == 200) {
      getGrouping()
    }
  }

  useEffect(() => {
    getauthority()
    getGrouping()
    getManagementList()
  }, [])
  return (
    <div style={{ display: "flex" }}>
      <div style={{marginRight:"20px",width:"500px"}}>
        <Card bordered>
          <div style={{ padding: '20px',height:"528px"}}>
            <Tabs defaultActiveKey="category1" activeKey={selectedCategory} onChange={handleCategoryChange}>
              {authorityList.map((category, index) => (
                <TabPane tab={category.name} key={category._id}>
                  <Form.Item
                    name="groupingName"
                    rules={[{ required: true, message: 'Please input Entry!' }]}
                  >
                    <Input value={groupingName} onChange={(e) => setGroupingName(e.target.value)} style={{ marginRight: "10px" }} />
                    {
                      !grouping_id?<Button type="primary" htmlType="submit" onClick={() => { getGroupingAdd() }}>
                      新增分组
                    </Button>:
                    <Button type="primary" htmlType="submit" onClick={() => { groupingUpdate() }}>
                      编辑分组
                    </Button>
                    }
                  </Form.Item>
                  <Table<DataType> pagination={false} rowSelection={rowSelection} columns={grouping_columns} dataSource={grouping_data} />
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Card>
      </div>

      <div style={{height:"500px"}}>
        <Card
          title="词条管理"
          actions={
            <Button onClick={showModal}>新增词条</Button>
          }
          bordered
          headerBordered
          style={{height:"600px",width:"1000px"}}
        >
          <Modal title="编辑词条" closable={false} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
            <div style={{ maxWidth: 600}}>
              <Form
                form={form}
                variant={variant || 'filled'}
                initialValues={{
                  variant: 'filled',
                  id: id,
                  authority: authority,
                  grouping: grouping,
                  entry: entry,
                  name: name,
                  content: content,
                  state: state
                }}
                onFinish={onFinish}
              >
                {/* authority 字段 */}
                <Form.Item
                  label="词条权限"
                  name="authority"
                  rules={[{ required: true, message: 'Please input Authority!' }]}
                >
                  <Select
                    value={authority?._id}  // 使用 _id 作为 value
                    onChange={(e) => {
                      const selectedAuthority = authorityList.find(item => item._id === e);
                      setAuthority(selectedAuthority); // 更新 authority 为完整对象
                    }}
                  >
                    {authorityList.map((item, index) => (
                      <Select.Option key={index} value={item._id} name="authority">
                        {item.name}
                      </Select.Option>
                    ))}
                  </Select>

                </Form.Item>

                {/* grouping 字段 */}
                <Form.Item
                  label="词条分组"
                  name="grouping"
                  rules={[{ required: true, message: 'Please input Grouping!' }]}
                >
                  <Select
                    value={grouping?._id} // 如果 grouping 是对象，确保它有 _id
                    onChange={(e: string) => {
                      const selectedGrouping = groupingList.find(item => item._id === e);
                      setGrouping(selectedGrouping); // 更新 grouping 为对象
                    }}
                  >
                    {groupingList.map((item, index) => (
                      <Select.Option key={index} value={item._id} name="grouping">
                        {item.name}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>


                {/* entry 字段 */}
                <Form.Item
                  label="词条编码"
                  name="entry"
                  rules={[{ required: true, message: 'Please input Entry!' }]}
                >
                  <Input value={entry} onChange={(e) => setEntry(e.target.value)} />
                </Form.Item>

                {/* name 字段 */}
                <Form.Item
                  label="词条名称"
                  name="name"
                  rules={[{ required: true, message: 'Please input Name!' }]}
                >
                  <Input value={name} onChange={(e) => setName(e.target.value)} />
                </Form.Item>

                {/* content 字段 */}
                <Form.Item
                  label="词条内容"
                  name="content"
                  rules={[{ required: true, message: 'Please input Content!' }]}
                >
                  <Input.TextArea rows={5} value={content} onChange={(e) => setContent(e.target.value)} />
                </Form.Item>

                {/* state 字段 */}
                <Form.Item label="启用状态" name="state">
                  <Radio.Group onChange={(e) => setState(e)} value={state}>
                    <Radio value={true}>启用</Radio>
                    <Radio value={false}>禁用</Radio>
                  </Radio.Group>
                </Form.Item>

                <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
                  {
                    id ? <Button type="primary" htmlType="submit" onClick={() => { getUpdate() }}>
                      编辑
                    </Button> :
                      <Button type="primary" htmlType="submit" onClick={() => { getAdd() }}>
                        新增
                      </Button>
                  }
                  <Button type="primary" htmlType="submit" onClick={() => { handleOk() }}>
                    取消
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </Modal>

          <div style={{ display: 'flex' }}>
            <Form.Item label="词条名称" name="so_name" initialValue={so_name}>
              <Input
                value={so_name}
                onChange={(e) => setSo_Name(e.target.value)}  // 更新输入框的值
                onKeyDown={getName}  // 监听键盘事件，判断是否是回车键
              />
            </Form.Item>
            <Form.Item label="词条权限" name="so_college" initialValue={authority}>
              <Select clearable value={so_state} placeholder='全部状态' onChange={(value: string) => { getState(value) }}>
                {optionList.map((item, index) => (
                  <Select.Option key={index} value={item.name}>
                    {item.value}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </div>

          <div>
            <Table<DataType> pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data} />
          </div>
          <Pagination
            total={total}
            defaultPageSize={pageSize}
            onChange={onChange}
            onCurrentChange={onCurrentChange}
            onPageSizeChange={onPageSizeChange}
          />
        </Card>
      </div >
    </div >
  );
}